var video;
var movieScreen;
$(document).on('pageinit', "#mv_html", function(e,eventData){
    $("title").html("歌曲");
    var audio = document.getElementById('audioPlayer');
    audio.pause();

    var container, scene, camera, renderer, controls, stats;
    var keyboard = new THREEx.KeyboardState();

// custom global variables
    var  videoImage, videoImageContext, videoTexture;

    if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
    var mesh, geometry, material;

    var mouseX = 0, mouseY = 0;
    var start_time = Date.now();

    var windowHalfX = window.innerWidth / 2;
    var windowHalfY = window.innerHeight / 2;

    init();
    animate();

// FUNCTIONS
    function init(){
        container = document.getElementById( 'mvCavus' );

        // Bg gradient

        var canvas = document.createElement( 'canvas' );
        canvas.width = 32;
        canvas.height = window.innerHeight;

        var context = canvas.getContext( '2d' );

        var gradient = context.createLinearGradient( 0, 0, 0, canvas.height );
        gradient.addColorStop(0, "#1e4877");
        gradient.addColorStop(0.5, "#4584b4");

        context.fillStyle = gradient;
        context.fillRect(0, 0, canvas.width, canvas.height);

        container.style.background = 'url(' + canvas.toDataURL('image/png') + ')';
        container.style.backgroundSize = '32px 100%';

        //

        camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 3000 );
        camera.position.z = 6000;

        scene = new THREE.Scene();

        geometry = new THREE.Geometry();

        var texture = THREE.ImageUtils.loadTexture( 'images/cloud10.png', null, animate );
        texture.magFilter = THREE.LinearMipMapLinearFilter;
        texture.minFilter = THREE.LinearMipMapLinearFilter;

        var fog = new THREE.Fog( 0x4584b4, - 100, 3000 );

        material = new THREE.ShaderMaterial( {

            uniforms: {

                "map": { type: "t", value: texture },
                "fogColor" : { type: "c", value: fog.color },
                "fogNear" : { type: "f", value: fog.near },
                "fogFar" : { type: "f", value: fog.far }

            },
            vertexShader: document.getElementById( 'vs' ).textContent,
            fragmentShader: document.getElementById( 'fs' ).textContent,
            depthWrite: false,
            depthTest: false,
            transparent: true

        } );

        var plane = new THREE.Mesh( new THREE.PlaneGeometry( 64, 64 ) );

        for ( var i = 0; i < 8000; i++ ) {

            plane.position.x = Math.random() * 1000 - 500;
            plane.position.y = - Math.random() * Math.random() * 200 - 20;
            plane.position.z = i;
            plane.rotation.z = Math.random() * Math.PI;
            plane.scale.x = plane.scale.y = Math.random() * Math.random() * 1.5 + 0.5;

            THREE.GeometryUtils.merge( geometry, plane );
        }

        mesh = new THREE.Mesh( geometry, material );
        scene.add( mesh );

        mesh = new THREE.Mesh( geometry, material );
        mesh.position.z = - 8000;
        scene.add( mesh );

        //document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        window.addEventListener( 'resize', onWindowResize, false );


        ///////////
        // VIDEO //
        ///////////

        // create the video element
        video = document.createElement( 'video' );
        $(video).hide();
        videoImage = document.createElement( 'canvas' );

        videoImage.width = 480;
        videoImage.height = 320;

        videoImageContext = videoImage.getContext( '2d' );
        // background color if no video present
        videoImageContext.fillStyle = '#000000';
        videoImageContext.fillRect( 0, 0, videoImage.width, videoImage.height );

        videoTexture = new THREE.Texture( videoImage );
        videoTexture.minFilter = THREE.LinearFilter;
        videoTexture.magFilter = THREE.LinearFilter;

        var movieMaterial = new THREE.MeshBasicMaterial( { map: videoTexture, overdraw: true, side:THREE.DoubleSide } );
        // the geometry on which the movie will be displayed;
        // 		movie image will be scaled to fit these dimensions.
        var movieGeometry = new THREE.PlaneGeometry( 4, 2.25, 1, 1 );
        movieScreen = new THREE.Mesh( movieGeometry, movieMaterial );
        //THREE.GeometryUtils.merge(geometry,movieGeometry );
        movieScreen.position.set(0,4,0);
        //movieScreen.rotation.x = -Math.PI / 3;
        movieScreen.rotation.y = -Math.PI / 5;
        //movieScreen.rotation.z = -Math.PI / 2;
        scene.add(movieScreen);
        //camera.position.set(0,10,100);
        //camera.lookAt(movieScreen.position);

        renderer = new THREE.WebGLRenderer( { antialias: true } );
        renderer.setSize( window.innerWidth, window.innerHeight );
        container.appendChild( renderer.domElement );
    }

    function onDocumentMouseMove( event ) {

        mouseX = ( event.clientX - windowHalfX ) * 0.25;
        mouseY = ( event.clientY - windowHalfY ) * 0.15;

    }

    function onWindowResize( event ) {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();

        renderer.setSize( window.innerWidth, window.innerHeight );

    }
    var position;

    function animate(){
        requestAnimationFrame( animate );
        render();
        update();
    }

    function update(){
        if ( keyboard.pressed("p") )
            video.play();

        if ( keyboard.pressed("space") )
            video.pause();

        if ( keyboard.pressed("s") ) // stop video
        {
            video.pause();
            video.currentTime = 0;
        }

        if ( keyboard.pressed("r") ) // rewind video
            video.currentTime = 0;
        TWEEN.update();
        //controls.update();
        //stats.update();
    }

    function render(){
        if ( video.readyState === video.HAVE_ENOUGH_DATA )
        {
            videoImageContext.drawImage( video, 0, 0 );
            if ( videoTexture )
                videoTexture.needsUpdate = true;
        }

        position = ( ( Date.now() - start_time ) * 0.03 ) % 8000;
        //camera.position.x += ( mouseX - camera.position.x ) * 0.01;
        //camera.position.y += ( - mouseY - camera.position.y ) * 0.01;
        camera.position.y = 10;
        camera.position.z = - position + 8000;
        movieScreen.position.x = camera.position.x;
        //movieScreen.position.y = camera.position.y;
        movieScreen.position.z = camera.position.z-8;
        //camera.lookAt(movieScreen.position);
        renderer.render( scene, camera );
    }
});